package com.mall.action;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mall.bean.User;
import com.mall.service.UserService;
import com.mall.uitl.JWTTokenUtil;
import com.mall.uitl.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author lwd1513
 * @date 2022-04-15 16 40
 * discription
 */
@RestController
@RequestMapping("/UserController")
public class UserController {

    Logger logger = LoggerFactory.getLogger(this.getClass());//创建一个日志对象

    @Autowired
    private UserService userService;
    @Autowired
    JWTTokenUtil jwtTokenUtil;

    @RequestMapping("/userLogin")
    public JsonUtil userLoginByUserName(String name, String password) {

        logger.debug("进入到了 userLoginByUserName方法里面");

        User userLogin = userService.userLoginByUserName(name, password);

        ObjectMapper objectMapper = new ObjectMapper();  //Gosn gson = new Gson()

        JsonUtil jsonUtil = new JsonUtil();

        HashMap<String, Object> map = new HashMap<>();
        if (userLogin != null) {

            String userInfo = null;
            try {
                userInfo = objectMapper.writeValueAsString(userLogin);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg(e.getMessage());
                return jsonUtil;
            }
            //登录成功 用户信息被使用后 密码要设置为空
            userLogin.setPassword("");

            String jsonJwt = jwtTokenUtil.getEncodeToken(userInfo);

            map.put("token", jsonJwt);
            map.put("userInfo", userLogin);

            //System.out.println("对用户做JWT加密后的结果为:" + jsonJwt);
            jsonUtil.setCode(0);
            jsonUtil.setData(map);

        } else {
            jsonUtil.setCode(1);
            jsonUtil.setMsg("登录失败，用户名密码不正确");
        }
        return jsonUtil;

    }


}
